
import 'package:boss/main.dart';
import 'package:boss/models/offers.dart' as offersResponse;
import 'package:boss/ui/page/offersManagement/constant/offers_constant.dart';
import 'package:boss/ui/page/offersManagement/page/plusOffersMode/page/planOffers/model/plan_menu_discount.dart';
import 'package:boss/ui/page/offersManagement/page/plusOffersMode/page/provider/base_provider.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';

class PlanOffersProvider extends BaseProvider {
  offersResponse.Offers data;

  PlanOffersProvider({offersResponse.Offers data}) {
    super.initData(data: data);
    this.data = data;
  }

  List<PlanMenuDiscount> menus;

  setMenus(List<PlanMenuDiscount> value) {
    if (data != null) {
      data.planMenuDiscountList.forEach((item) {
        var current = value.firstWhere((temp) => temp.menu.menuId == item.menuId, orElse: () => null);

        if (current != null) {
          current.discountRate = item.discountRate.toString();
          current.controller.text = item.discountRate.toString();
        }
      });
    }

    menus = value;

    notifyListeners();
  }

  setMenusDiscountRate(int rate) {
    menus.forEach((item) {
      item.discountRate = rate.toString();
      item.controller.text = rate.toString();
    });

    notifyListeners();
  }

  Future<bool> addPlanOffers() async {
    try {
      if (offerName == null || offerName == '') {
        toast('请填写优惠名称');
        return false;
      }
      List<Map<String, dynamic>> listMenuDiscount = [];
      menus.forEach((item) {
        if (item.discountRate != '') {
          listMenuDiscount.add({
            'discountName': offerName,
            'discountRate': int.parse(item.discountRate),
            'menuId': item.menu.menuId,
            'menuName': item.menu.menuName,
          });
        }
      });

      if (listMenuDiscount.length == 0) {
        toast('请输入菜品分类折扣');
        return false;
      }

      showLoadingToast();

      Map<String, dynamic> data = {
        'listMenuDiscount': listMenuDiscount,
        'storeDiscountStandard': {
          'activityName': offerName,
          'activityType': activityType,
          'discountType': OffersConstant.plan_discount,
          'type': OffersConstant.order_offers,
          'supportQrcode': 0,
        },
      };

      setDateTimeForHttpData(data);

      var result = await api.addPlanDiscount(data);

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }
      toast('添加成功');
      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }
}
